package net.wansho.listener;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import net.wansho.po.Student;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

/**
 * Author：汤小洋
 * Date：2023-11-03 10:48
 * Description：消费者
 */
@Component
public class MsgListener {

    @RabbitListener(queues = "queue1")
    // public void readMsg(String msg){
    public void readMsg(Student stu){
        // System.out.println("接收到消息：" + msg);
        System.out.println("接收到消息：" + stu);
    }

    @RabbitListener(queues = "${shop.queue}")
    public void readMsg2(Student stu){
        System.out.println("接收到消息：" + stu);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("queue3"),
            exchange = @Exchange(value = "exchange2.fanout", type = ExchangeTypes.FANOUT)
    ))
    public void readMsg3(String msg){
        System.out.println("消费者1：" + msg);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("queue4"),
            exchange = @Exchange(value = "exchange2.fanout", type = ExchangeTypes.FANOUT)
    ))
    public void readMsg4(String msg){
        System.out.println("消费者2：" + msg);
    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("queue5"),
            exchange = @Exchange(value = "exchange3.direct", type = ExchangeTypes.DIRECT),
            key = "hello"
    ))
    public void readMsg5(String msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag){
        System.out.println("读取消息：" + msg);

        // todo 处理业务逻辑

        // 确认消息，处理消息成功
        // channel.basicAck(tag, false); // 参数：消息标签，是否批量确认

        // 未确认，处理消息失败
        // channel.basicNack(tag, false, false); // 参数：消息标签，是否批量确认，是否重回队列

        // 拒绝消息
        channel.basicReject(tag, false); // 参数：消息标签，是否重回队列

    }


    @SneakyThrows
    @RabbitListener(queues = "normal.queue")
    public void readMsg6(String msg,  Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag){
        // 模拟：如果是偶数，则业务处理正常，确认消息
        if(Integer.parseInt(msg.substring(2))%2 == 0){
            System.out.println("正常：" +  msg);
            channel.basicAck(tag,false);
        }else{
            // 如果是奇数，则业务处理失败，拒收消息，且不再重新放入队列
            channel.basicNack(tag,false,false);
        }
    }

    @SneakyThrows
    @RabbitListener(queues = "dead.queue")
    public void readMsg7(String msg,  Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag){
        System.out.println("死信：" + msg);
        channel.basicAck(tag, false);
    }

}
